package ai.zixing.mashibing.new_class.class07;

// https://leetcode.cn/problems/balanced-binary-tree/
public class Code02_BalancedBinaryTree {
    public static class TreeNode {
        public int val;
        public TreeNode left;
        public TreeNode right;

        TreeNode(int val) {
            this.val = val;
        }
    }

    public boolean isBalanced(TreeNode root) {
        return process(root).isBalanced;
    }

    public static class Info {
        public boolean isBalanced;
        public int height;

        public Info(boolean b, int h) {
            this.isBalanced = b;
            this.height = h;
        }
    }

    public static Info process(TreeNode x) {
        if (x == null) {
            return new Info(true, 0);
        }
        // 左树信息
        Info leftInfo = process(x.left);
        // 有树信息
        Info rightInfo = process(x.right);
        // 树的总高度
        int hight = Math.max(leftInfo.height, rightInfo.height) + 1;
        // 左树平衡，有树平衡，整体平衡
        boolean isBalanced = leftInfo.isBalanced && rightInfo.isBalanced
                && Math.abs(leftInfo.height - rightInfo.height) <= 1;
        return new Info(isBalanced, hight);
    }
}
